<template>
  <n-modal
    v-model:show="showDialog"
    preset="dialog"
    class="rounded-[24px]"
    title=""
    style="width: 440px"
    :closable="true"
    :show-icon="false"
    :close-on-esc="true"
    :mask-closable="true"
  >
    <div class="min-h-[100px]">
      <div v-if="facebookResult?.id">
        <!-- 已登录 -->
        <div :class="title">{{ $t("title.登录Alib2b") }}</div>
        <div class="flex justify-center text-0">
          <img class="w-20 h-20 rounded-full" :src="facebookResult?.picture.data.url" />
        </div>
        <div class="mt-2 text-center text-[18px] font-[400]">
          {{ facebookResult.name }}
        </div>
        <div class="text-center text-[16px] font-[300] text-[#5C5C5C]">
          {{ facebookResult.email }}
        </div>
        <div class="flex w-[320px] m-auto">
          <div
            @click="loginFacebookByCurrent"
            class="flex-1 mt-4 justify-center cursor-pointer flex border-[#0256FF] border-[1px] border-solid bg-[#0256FF] text-[#fff] py-[8px] rounded-[20px]"
          >
            <div class="flex gap-[8px] items-center text-[16px]">
              <n-icon :size="24">
                <LogoFacebook></LogoFacebook>
              </n-icon>
              {{ $t("button.使用此账号") }}
            </div>
          </div>
        </div>
        <div class="flex w-[320px] m-auto">
          <div
            @click="onClickLogoutFacebook"
            class="flex-1 mt-4 justify-center cursor-pointer flex text-[#0256FF] border-[#0256FF] border-[1px] border-solid bg-[#fff] py-[8px] rounded-[20px]"
          >
            <div class="flex gap-[8px] items-center text-[16px]">
              <n-icon :size="24">
                <LogoFacebook></LogoFacebook>
              </n-icon>
              {{ $t("button.切换账号") }}
            </div>
          </div>
        </div>

        <div class="font-light mt-4 text-[14px] text-[#5C5C5C]">
          <n-checkbox v-model:checked="agree"> </n-checkbox>
          <!-- {{ $t("tips.登录条款") }} -->
          El uso continuado significa que ha leído y aceptado la
          <span class="cursor-pointer text-[#0256FF]" @click="onClickShowArtical">
            Políticas de Privacidad
          </span>
          de Alib2b
          <!-- 等翻译确认后 再调整UI -->
          <!-- Al continuar, aceptas los
          <span class="text-[#0256FF]">Términos de Servicio</span> y la
          <span class="text-[#0256FF]">Política de Privacidad</span> de Alib2b -->
        </div>
      </div>
      <div v-else>
        <div :class="title">{{ $t("title.登录Alib2b") }}</div>
        <div class="font-light text-[16px] text-[#5C5C5C]">
          {{ $t("tips.登录提示语") }}
        </div>
        <div class="flex justify-center">
          <div
            @click="onClickFacebookLogin"
            class="my-6 cursor-pointer flex items-center gap-[8px] bg-[#0256FF] text-[#fff] py-[8px] px-[48px] rounded-[20px]"
          >
            <n-icon :size="24">
              <LogoFacebook></LogoFacebook>
            </n-icon>
            {{ $t("button.facebook登录") }}
          </div>
        </div>
      </div>
    </div>
    <n-modal
      v-model:show="showArtical"
      preset="dialog"
      class="rounded-[24px]"
      title=""
      style="width: 900px"
      :closable="true"
      :show-icon="false"
      :close-on-esc="true"
      :mask-closable="true"
    >
      <div class="h-[600px] flex flex-col">
        <div :class="title">{{ articalData.title }}</div>
        <div class="flex-1 h-0">
          <n-scrollbar style="height: 100%">
            <div v-html="articalData.content"></div>
          </n-scrollbar>
        </div>

        <div class="text-center pt-[20px]">
          <n-button size="large" type="primary" class="px-[100px]" @click="onClickAgree">
            {{ $t("button.同意并继续") }}
          </n-button>
        </div>
      </div>
    </n-modal>
  </n-modal>
</template>

<script setup>
import { ref } from "vue";
import { LogoFacebook } from "@vicons/ionicons5";
import { useUser } from "@/stores/user";
import { Session } from "@/utils/storage";
import { useRouter } from "vue-router";
import { useMessage } from "naive-ui";
import { artical } from "@/mock/data/artical";
import { getUserAgreement } from "@/api/common";
const message = useMessage();
const router = useRouter();
const facebookResult = ref({});
const showDialog = ref(false);
const title = "text-[24px] font-[400] text-center mb-[16px]";
const { facebookLoginHandler } = useUser();
const isDev = import.meta.env.MODE == "development";
const agree = ref(false);
const showArtical = ref(false);
const articalData = ref({});
const show = async () => {
  showDialog.value = true;
  FB.getLoginStatus(function (response) {
    if (isDev) {
      response.status = "connected";
    }
    // console.log("%c Line:22 🌰 response", "color:#f5ce50", response);
    if (response.status === "connected") {
      getFackbookUserInfo(false);
    }
  });
  const { data } = await getUserAgreement();
  articalData.value = data.data;
  if (!articalData.value.content) {
    articalData.value = artical.find((x) => x.title == "Políticas de privacidad");
  }
};

const onClickFacebookLogin = () => {
  FB.login(
    function (response) {
      // console.log("%c Line:279 🍒 登录结果", "color:#465975", response);
      if (isDev) {
        response.status = "connected";
      }
      if (response.status === "connected") {
        getFackbookUserInfo(true);
      }
    },
    { scope: "public_profile,email" }
  );
};

const getFackbookUserInfo = (autoLogin) => {
  FB.api("/me", { fields: "id,name,picture" }, async (response) => {
    if (isDev) {
      response = {
        name: "Bai Li",
        picture: {
          data: {
            url:
              "https://scontent-sea1-1.xx.fbcdn.net/v/t1.30497-1/84628273_176159830277856_972693363922829312_n.jpg?stp=c15.0.50.50a_cp0_dst-jpg_p50x50&_nc_cat=1&ccb=1-7&_nc_sid=7565cd&_nc_ohc=TeZ_H7ylGr0Q7kNvgENi8lp&_nc_ht=scontent-sea1-1.xx&edm=AP4hL3IEAAAA&oh=00_AYCXMBJ1cXzqWKylNn1rvoi8lnWFG89-XLgSLD9cVmv5kQ&oe=66ACA419",
          },
        },
        id: "222110469744362268",
        email: "baili@alib2b.com",
      };
    }

    facebookResult.value = response;
    // console.log("%c Line:288 🌰 登录信息", "color:#7f2b82", response);
    if (!autoLogin) return;
    await loginFacebookByCurrent();
  });
};

const loginFacebookByCurrent = async () => {
  if (!agree.value) {
    // message.warning(window.tt("confirm.同意政策"));

    onClickShowArtical();

    return;
  }
  await facebookLoginHandler({
    name: facebookResult.value.name,
    avatar: facebookResult.value.picture?.data?.url,
    account: facebookResult.value.id,
    email: facebookResult.value.email,
  });

  showDialog.value = false;
  let redirect_url = Session.get("redirect_url");
  if (redirect_url) {
    Session.remove("redirect_url");
    router.push(redirect_url);
  }
};

const onClickLogoutFacebook = () => {
  if (isDev) {
    facebookResult.value = {}; //测试用
  }
  try {
    FB.logout(function (response) {
      facebookResult.value = {};
    });
  } catch (error) {}
};

const onClickShowArtical = () => {
  showArtical.value = true;
};

const onClickAgree = () => {
  showArtical.value = false;
  agree.value = true;
};
defineExpose({ show });
</script>

<style lang="scss" scoped></style>
